/*
* Copyright 2010 ANDAGO INGENIERIA S.L.
*
* Licensed under the EUPL, Version 1.1 only (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/

package com.andago.alohaui;



import ieee_11073.part_10101.Nomenclature;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import es.libresoft.mdnf.FloatType;
import es.libresoft.openhealth.android.AgentMetric;
import es.libresoft.openhealth.android.AndroidAttribute;
import es.libresoft.openhealth.android.AndroidDateMeasure;
import es.libresoft.openhealth.android.AndroidValueMeasure;
import es.libresoft.openhealth.android.IAgentActionService;
import es.libresoft.openhealth.android.IAgentCallbackService;
import es.libresoft.openhealth.android.IAgentRegister;

import com.andago.utils.NomenclatureIEEE;


public class HowtoActivity extends Activity {	
	

	
	private ProgressDialog dialog;	
	
	
	/** The primary interface we will be calling on the service. */
    IAgentRegister mService;
    IAgentActionService actionService;
	
	String deviceName = "init";
	String stateAgent = "Operating";
	String measureAgent = null;
	String date = "init";
	Boolean measurementReceived =false;
	Boolean applicationReady = false;
	
	int attribute_code;
	int phID_device;
	String selection;
	
	Context context;

	
	private ArrayList<Integer> measuremtsDevice= new ArrayList<Integer>();
	private ArrayList<String> measurementValueArray=null;
	private ArrayList<Integer> measurementAttributeCodeArray=new ArrayList<Integer>();
	private CharSequence[] measurementAttributeNameArray;
	private ArrayList<Integer> measurementUnitArray=new ArrayList<Integer>();

	private View id;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      
      setContentView(R.layout.howtodevices);
   
      context=this;
      
      id = findViewById(R.id.idMonitorizacion);
      
  
  	
      
      Bundle extras  = getIntent().getExtras();
	  if (extras != null){
			deviceName = extras.getString("agent");
			selection = extras.getString(getString(R.string.selection_bundle));
			if (selection.equals(getString(R.string.measures_selection))){
				attribute_code = extras.getInt(getString(R.string.measurement_bundle));
				measuremtsDevice.add(attribute_code);
			}
				
			phID_device  = extras.getInt(getString(R.string.phidDevice_bundle));
	  }
	  
	  
	 
	  System.err.println("****************attribute_code: " + attribute_code);
	  System.err.println("****************selection: " + selection);
	  System.err.println("****************deviceName: " + deviceName);
	  System.err.println("****************measurement_name: " + attribute_code);
	  System.err.println("****************phID_device: " + phID_device);
		
	  
	  measurementValueArray = new ArrayList<String>();	
		
	  TextView text_instructions = (TextView) findViewById(R.id.texto_instruction);
	  
		

 
	  if ((phID_device >= 400) && (phID_device<=499)){
		  System.out.println("Instruccionessssssss");
		  text_instructions.setText(R.string.instructions_oxigen);
		  if (selection.equals(getString(R.string.devices_selection)))
			  {
			  measuremtsDevice=NomenclatureIEEE.getAttributesDevice10404();
			  System.out.println("Medidas posiblessss:" + measuremtsDevice.size());
			  }
		  
	  }
	  else  if ((phID_device >= 800) && (phID_device<=899)){
		  text_instructions.setText(R.string.instructions_temperature);
		  if (selection.equals(getString(R.string.devices_selection)))
			  measuremtsDevice=NomenclatureIEEE.getAttributesDevice10408();	  	  
    	}else  if ((phID_device >= 1500) && (phID_device<=1599)){		  
		  text_instructions.setText(R.string.instructions_weight);
		  if (selection.equals(getString(R.string.devices_selection)))
		      measuremtsDevice=NomenclatureIEEE.getAttributesDevice10415();
		  }
		  

		  
	  
	    
	    
		
      Button button_ok = (Button) findViewById(R.id.okButton);
      
      button_ok.setOnClickListener(new OnClickListener() {
          public void onClick(View view) {

        	  CharSequence str = getString(R.string.message_receiving);
        	          	  
        	  dialog = ProgressDialog.show(HowtoActivity.this, "", 
                       str,true);
        	  
        	  new Thread() {
        		  @Override
				public void run() {
	        		  try {  
	        			  
	        			  while (!measurementReceived && !stateAgent.equals(getString(R.string.Disconected))){	        				 
	        				 System.err.println("...................");  				 
	 	        		     sleep(100);
	        		 	  }
	        			  
	        			  
	        			  
	        			  
	        		  } catch (Exception e) {
	        			  System.err.println("Exception: Not measurement: "+e.getMessage());
	        			  
	        		  }
	        		  
	        		  dialog.dismiss();	  
	        		  
	        		/*  if (stateAgent.equals(getString(R.string.Disconected))&&!measurementReceived)
	        			  
	        			  id.post(new Runnable() {
	        			        public void run() {
	        			        	Toast.makeText(context, getString(R.string.measures_not_received), Toast.LENGTH_LONG).show();
	        			          }
	        			        });
	        		  
	        		  else if (measurementReceived)	  
	        			  		startingActivity();*/

      			  		startingActivity();
	        		
	        		  
        		  }

				private void startingActivity() {
					// TODO Auto-generated method stub
					
					
					  Intent intent = new Intent(HowtoActivity.this, MeasuresActivity.class);
	      			  int id=0;
	      			  if(measurementValueArray.size()>0){
	      				System.out.println("measurementArray HowToActivity Size "+ measurementValueArray.size());
	      			  	intent.putStringArrayListExtra(getString(R.string.measurement_bundle), measurementValueArray);
	      			    intent.putIntegerArrayListExtra(getString(R.string.attribute_bundle), measurementAttributeCodeArray);
	      			    intent.putIntegerArrayListExtra(getString(R.string.unit_bundle), measurementUnitArray);
	      			  	
	      			  }
	      			 intent.putExtra(getString(R.string.selection_bundle), selection);
	      			
	      			 startActivity(intent);   		
					
				}
				
				
        		}.start();
              }
            });
      
  		// ***************************************************
		// binding to the Manager service and to the Agent Action service
		// ***************************************************
		  
	    bindService(new Intent(IAgentRegister.class.getName()),	mConnection, Context.BIND_AUTO_CREATE);
	    
	    bindService(new Intent(IAgentActionService.class.getName()),agentConnection, Context.BIND_AUTO_CREATE);
   
    
    }

    @Override
	public void onStop(){
		super.onStop();
		this.finish();
	}
	@Override
	public void onDestroy(){
		super.onDestroy();
	}
	
    private void showMeasures(){
	
				
	    
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);  
	  
	    builder.setTitle("Choose an option");
	    
	    builder.setMultiChoiceItems(measurementAttributeNameArray,null,new DialogInterface.OnMultiChoiceClickListener() {
	    	public void OnMultiChoiceClickListener(DialogInterface dialog, int item,boolean isChecked) {
	    		
	    		    	    		
	    	}

			@Override
			public void onClick(DialogInterface dialog, int which,
					boolean isChecked) {
				// TODO Auto-generated method stub
				
			}
	    });
	    
	    //builder.show();
	   AlertDialog alert = builder.create();
	   alert.show();
	
		
	}

    
    // implementation of the agent callbacks IDL
       private IAgentCallbackService mCallback = new IAgentCallbackService.Stub() {


   		public void agentStateChanged(String state) throws RemoteException {
   			// TODO Auto-generated method stub
   			
   			
   			System.out.println("Agente in estate: " + state);
   			stateAgent = state;
   			/*
   			handler.post(doUpdateState);
   		   */
   			
   		}

		@Override
		public void metricReceived(AgentMetric metric) throws RemoteException {
			// TODO Auto-generated method stub
			

			
			if (!measurementReceived){		
					boolean keepUnit=false;
					
					List measures = metric.getMeasures();
					List attributes = metric.getAttributes();
					
					Iterator imeasures = measures.iterator();
					Iterator iattributes = attributes.iterator();
					

		   			Object measure;
		   			Object attribute;
		   			
		   			System.out.println("***************list measures metricReceived: "+ measures.size());
		   			System.out.println("***************list attributes metricReceived: "+ attributes.size());
		   			
		   			while (imeasures.hasNext()){	   				
		   						   				
		   				int i=1;
		   				System.out.println("***************Medida "+ i);
		   				
		   				measure = imeasures.next();
		   				
		   				if (measure instanceof AndroidValueMeasure){
		   					
		   					try {			
		   						System.out.println("***************Es de tipo AndroidValue ");
		   						//System.out.println("valor: " + ((AndroidValueMeasure)measure).getFloatType());
		   						//DecimalFormat formater = new DecimalFormat("00.00");
		   						
		   						FloatType aux_measure = ((AndroidValueMeasure)measure).getFloatType();
		   						Double doubleMeasure = aux_measure.doubleValueRepresentation();
		   						System.out.println("***************Medida = "+ doubleMeasure);
		   						measureAgent = doubleMeasure.toString();
		   						System.out.println("***************Medida = "+ measureAgent);
		   											
		   					} catch (Exception e) {
		   						// TODO Auto-generated catch block
		   						e.printStackTrace();
		   					}
		   					
		   					
		   					while (iattributes.hasNext()){
		   						int j=1;
		   						int iAttributeName=0;
		   								   		
			   					attribute = iattributes.next();
			   					
			   					
			   					if (attribute instanceof AndroidAttribute){
				   					try {
				   						
				   						System.out.println("***************Atributo "+ j);
				   						
				   						AndroidAttribute androidAttribute = (AndroidAttribute)attribute;
				   					    int type = androidAttribute.getAttrId();
				   					    int code = androidAttribute.getCode();
				   					    System.out.println("***************Type attribute metricReceived: "+ type);
				   					    System.out.println("***************Code attribute metricReceived: "+ code);
				   					    
				   					    System.out.println("***************measuremtsDevice.contains(" + code +"): "+ measuremtsDevice.contains(code));
				   					    System.out.println("***************measurementValueArray.contains("+ measureAgent + "): " + measurementValueArray.contains(measureAgent));
				   					    
				   					    
				   					    if ((type==Nomenclature.MDC_ATTR_ID_TYPE)&& (measuremtsDevice.contains(code))&&
				   					    		!measurementValueArray.contains(measureAgent)){  
				   					    	
				   					    		keepUnit=true;
				   					    		System.out.println("***************añadido value: " + measureAgent);
				   					    		measurementValueArray.add(measureAgent);	
				   					    		System.out.println("***************añadidos attribute: " + code);
				   					    		measurementAttributeCodeArray.add(code);
				   					    		measurementAttributeNameArray[iAttributeName++]=NomenclatureIEEE.calculateAttribute(code);
				   					    		
				   					    }
				   					    
				   					    if ((type==Nomenclature.MDC_ATTR_UNIT_CODE)){
				   					    	if (keepUnit){
					   		 					System.out.println("***************añadidos unit: "+code);
					   							measurementUnitArray.add(code);
					   							keepUnit=false;
				   							}
				   					    }
				   					    	
				   						
				   					}catch (Exception e) {
				   						e.printStackTrace();
				   					}
				   				 }
			   					j++;
		   					}  					
		   						   					
		   				}
		   				
		   				if (measure instanceof AndroidDateMeasure) {
		   					System.out.println("***************Es de tipo AndroidDate ");
		   					System.out.println("timestamp: " + (AndroidDateMeasure)measure);
		   					date = ((AndroidDateMeasure)measure).toString();
		   					// RPO no muestro nada de momento
		   					//handler.post(doUpdateGUI);
		   				}
		   				
		   				i++;
		   			  }	
		   			
		   			System.out.println("***************measurementAttributeArray.containsAll(measuremtsDevice) "+ measurementAttributeCodeArray.containsAll(measuremtsDevice));
		   			
		   			if(measurementAttributeCodeArray.containsAll(measuremtsDevice))		   								
		   					measurementReceived=true;
			}
			
		}
      };
      
      
      //  implement the ServiceConnection interface 
      private ServiceConnection mConnection = new ServiceConnection() {

   	public void onServiceConnected(ComponentName name, IBinder service) {
   		// TODO Auto-generated method stub
   		
   		System.out.println("onServiceConnected mConnection");	
   		mService = IAgentRegister.Stub.asInterface(service);
   		try {
   			
   			System.out.println("onServiceConnected mConnection deviceName" +deviceName);
   			if (mCallback==null) System.out.println("onServiceConnected mConnection mCallback es nulo");
   			mService.registerAgentCallback(deviceName, mCallback);
   		} catch (RemoteException e) {
   			// TODO Auto-generated catch block
   			e.printStackTrace();
   		}
   	}

   	public void onServiceDisconnected(ComponentName name) {
   		// TODO Auto-generated method stub
   		System.out.println("I'm in ServiceDisconnected");	
   		mService = null;
   	}

   	   

   	   
      };
      
      private ServiceConnection agentConnection = new ServiceConnection() {

   	public void onServiceConnected(ComponentName name, IBinder service) {
   		// TODO Auto-generated method stub
   		actionService = IAgentActionService.Stub.asInterface(service);
   	}

   	public void onServiceDisconnected(ComponentName name) {
   		// TODO Auto-generated method stub
   		System.out.println("I'm in ServiceDisconnected");	
   		actionService = null;
   	}

   	   
   	  
    
      };

    

}
    
